package com.abo.yaas.webservice.hibernate;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EntityManagerFilter implements Filter {

    @Override
    public void destroy() {
        EMF.close();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
        throws IOException, ServletException {
        
        final EntityManager em = EntityManagerUtils.getEntityManager();
        try {
            if (em == null) {
                EntityManagerUtils.setEntityManager(EMF.get().createEntityManager());
            }
            chain.doFilter(request, response);
            EntityManagerUtils.removeEntityManager();
        } finally {
            try {
                if (em != null) {
                    em.close();
                }
            } catch (final Throwable t) {
                t.printStackTrace();
            }
        }
    }

    @Override
    public void init(FilterConfig config) {
        destroy();
        EntityManagerUtils.setEntityManager(EMF.get().createEntityManager());
    }
}
